import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import _ from 'lodash';
import moment from 'moment';

import { upload } from '@/utils/request';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Button,
  Card,
  Col,
  DatePicker,
  Input,
  Upload,
  Row,
  Select,
  Radio,
  message,
} from 'antd';

import { UploadOutlined } from '@ant-design/icons';
import { base_url } from '../../../../../config/request.config';
import '@ant-design/compatible/assets/index.css';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { Item } = Form;
interface PosthouseContractAddInfoProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  match: { params: { pid: number } };
  submitting: boolean;
  posthouse: any;
  ContractAdd: any;
}

interface PosthouseContractAddInfoState{
  fileList:any[]
}
@connect(
  ({
    posthouseContractAdd,
    loading,
  }: {
    posthouseContractAdd: any;
    loading: { effects: { [key: string]: boolean } };
  }) => ({
    ContractAdd: posthouseContractAdd,
    submitting: loading.effects['posthouseContractAdd/save'],
  }),
)
class posthouseContractAdd extends Component<PosthouseContractAddInfoProps,
PosthouseContractAddInfoState> {
  timer: any = null;

  state: PosthouseContractAddInfoState = {
    fileList: [],
  };

  componentDidMount() {
    const { match: { params: { pid } } } = this.props;
    if (pid) this.fetchDetailInfo(pid);

    // 初始拉取所属商户
    const { dispatch } = this.props;
    dispatch({ type: 'posthouseContractAdd/fetchFranchisees' });
    dispatch({ type: 'posthouseContractAdd/fetchContractPartys' }); // 初始拉取合同主体

    // 初始拉取所有未签约驿站
    dispatch({
      type: 'posthouseContractAdd/fetchPosthouse',
      payload: { name: '' },
    });
  }

  componentDidUpdate(prevProps: any) {
    const { match: { params: { pid } } } = this.props;
    if (pid && pid !== prevProps.match.params.pid) {
      this.fetchDetailInfo(pid);
    }

    const { ContractAdd: { detail: ContractAdd } } = this.props;
    if (!_.isEqual(prevProps.ContractAdd.detail, ContractAdd)) {
      this.setValue();
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({ type: 'posthouseContractAdd/clean' });
  }

  setValue = () => {
    const { ContractAdd: { detail: ContractAdd } } = this.props;
    const {
      start_day,
      end_day,
      delivery_service_fee,
      sending_service_fee,
      deposit_service_fee,
      sms_service_fee,
    } = ContractAdd;

    const values: any = _.pick(
      ContractAdd,
      'fcs_id',
      'party_a_name',
      'posthouse_id',
      'contract_num',
      'withdraw_charge_ratio',
    );

    if (start_day && end_day) {
      values.start_end_time = [moment(start_day, 'YYYY-MM-DD'), moment(end_day, 'YYYY-MM-DD')];
    }
    // 派件服务费
    if (delivery_service_fee) {
      values.delivery_service_fee = Math.floor(delivery_service_fee * 100) / 10000;
    }
    // 揽件服务费
    if (sending_service_fee) {
      values.sending_service_fee = Math.floor(sending_service_fee * 100) / 10000;
    }
    // 短信服务费
    if (deposit_service_fee) {
      values.deposit_service_fee = Math.floor(deposit_service_fee * 100) / 10000;
    }
    // 派件服务费
    if (sms_service_fee) {
      values.sms_service_fee = Math.floor(sms_service_fee * 100) / 10000;
    }

    const new_values = {
      ...values,
      fcs_id: {
        key: values.fcs_id,
        label: '',
      },
    };

    const fileList = ContractAdd.file_link
      ? ContractAdd.file_link.split().reduce((origin: any, item: any, index: number) => {
        origin.push({ uid: index, name: '附件', url: item });
        return origin;
      }, []) : [];

    const { form: { setFieldsValue } } = this.props;
    this.setState({ fileList }, () => setFieldsValue(new_values));
  };

  fetchDetailInfo = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'posthouseContractAdd/fetch',
      payload: { id },
    });
  };

  handleSearchFcs = (name: string) => {
    clearTimeout(this.timer);

    this.timer = setTimeout(() => {
      const { dispatch } = this.props;
      dispatch({
        type: 'posthouseContractAdd/fetchFranchisees',
        payload: { name },
      });
    }, 500);
  };

  handleSelectFcs = ({ key }: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'posthouseContractAdd/generateNum',
      payload: { fcs_id: key },
    });
  };

  /**
   * 上传文件
   */
  handleUpload = ({ file }: any) => {
    const fileList = [
      {
        uid: 1,
        name: file.name.length > 5 ? `${file.name.substring(0, 5)}....pdf` : file.name,
        url: file.url,
      },
    ];

    this.setState({ fileList });
  };

  /* 基本信息 */
  renderBasicInfoElem = () => {
    const { fileList } = this.state;
    const {
      form: { getFieldDecorator },
      ContractAdd: { franchiseesList: { list = [] } },
      ContractAdd: { contractpartyslist = [] },
      ContractAdd: { signingStationList = [], generate = '' },
    } = this.props;

    const props: any = {
      accept: '.pdf',
      action: '',
      onChange: this.handleUpload,
      beforeUpload: this.beforeUpload.bind(this),
    };

    const placeholder = signingStationList.length <= 0 ? '请先选择所属商户' : '请选择签约驿站';

    return (
      <Card
        title="基本信息"
        bordered={false}
        className="paddingB10"
      >
        <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
          <Col md={8} sm={24}>
            <Item label="所属商户" colon={false}>
              {getFieldDecorator('fcs_id', {
                rules: [{ required: true, message: '请选择所属商户' }],
              })(
                <Select
                  placeholder="请选择"
                  showSearch
                  labelInValue
                  onSearch={this.handleSearchFcs}
                  onChange={this.handleSelectFcs}
                  filterOption={(input: any, option: any) => option.props.children
                    .toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {list.map(
                    (item: any) => item.status === 1 && (
                    <Option key={item.id} value={item.id}>{item.name}</Option>
                    ),
                  )}
                </Select>,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Item label="合同主体" colon={false}>
              {getFieldDecorator('party_a_name', {
                rules: [{ required: true, message: '请选择合同主体' }],
              })(
                <Select
                  showSearch
                  placeholder="请选择合同主体"
                  defaultActiveFirstOption={false}
                  showArrow={false}
                  notFoundContent={null}
                  filterOption={(input: any, option: any) => option.props.children
                    .toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {contractpartyslist.map((item: any) => (
                    <Option key={item} value={item}>{item}</Option>
                  ))}
                </Select>,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Item label="签约驿站" colon={false}>
              {getFieldDecorator('posthouse_id', {
                rules: [{ required: true, message: '请选择签约驿站' }],
              })(
                <Select
                  showSearch
                  placeholder={placeholder}
                  defaultActiveFirstOption={false}
                  showArrow={false}
                  notFoundContent={null}
                  filterOption={(input: any, option: any) => option.props.children
                    .toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {signingStationList.map((item: any) => (
                    <Option key={item.id} value={item.id}>{item.name}</Option>
                  ))}
                </Select>,
              )}
            </Item>
          </Col>
        </Row>
        <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
          <Col md={8} sm={24}>
            <Item label="合同周期" colon={false}>
              {getFieldDecorator('start_end_time', {
                rules: [{ required: true, message: '请选择合同周期' }],
              })(
                <RangePicker style={{ width: '100%' }} />,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Item label="合同编号" colon={false}>
              {getFieldDecorator('contract_num', {
                initialValue: generate,
                rules: [{ required: true, message: '请输入合同编号' }],
              })(
                <Input style={{ width: '100%' }} placeholder="请输入合同编号" />,
              )}
            </Item>
          </Col>
          <Col md={8} sm={24}>
            <Item label="上传合同" colon={false}>
              {getFieldDecorator('fileLink', {
                initialValue: fileList[0],
                rules: [{ required: true, message: '请上传合同文件' }],
              })(
                <Upload {...props} fileList={fileList}>
                  <Button
                    type="primary"
                    ghost
                    style={{ fontSize: 12 }}
                    size="small"
                  >
                    <UploadOutlined />
                    上传文件
                  </Button>
                </Upload>,
              )}
            </Item>
          </Col>
        </Row>
      </Card>
    );
  };

  // 结算信息
  renderSettlementElem = () => {
    const {
      form: { getFieldDecorator },
      submitting,
    } = this.props;

    return (
      <Card title="结算信息" bordered={false}>
        <Row gutter={{ md: 8, xl: 48, lg: 48 }}>
          <Col md={10} sm={24}>
            <div
              className="dottedBox marginB20"
              style={{ paddingBottom: 4 }}
            >
              <div className="subtitle marginB16">
                服务费抽成
                <Radio.Group value={1} style={{ marginLeft: 12 }}>
                  <Radio value={1}>充值模式</Radio>
                </Radio.Group>
              </div>
              <Item
                colon={false}
                label="派件服务费（￥）/件"
                className="marginB12"
              >
                {getFieldDecorator('delivery_service_fee', {
                  rules: [{ required: true, message: '派件服务费不能为空,且必须为数字' }],
                })(
                  <Input
                    suffix="元"
                    type="number"
                    style={{ width: '90%' }}
                    placeholder="请输入"
                  />,
                )}
              </Item>
              <Item
                colon={false}
                label="揽件服务费（￥）/件"
                className="marginB8"
              >
                {getFieldDecorator('sending_service_fee', {
                  rules: [{ required: true, message: '揽件服务费不能为空,且必须为数字' }],
                })(
                  <Input
                    suffix="元"
                    type="number"
                    style={{ width: '90%' }}
                    placeholder="请输入"
                  />,
                )}
              </Item>
              <Item
                colon={false}
                label="寄存服务费（￥）/件"
                className="marginB8"
              >
                {getFieldDecorator('deposit_service_fee', {
                  rules: [{ required: true, message: '寄存服务费不能为空,且必须为数字' }],
                })(
                  <Input
                    suffix="元"
                    type="number"
                    style={{ width: '90%' }}
                    placeholder="请输入"
                  />,
                )}
              </Item>
            </div>
          </Col>
          <Col md={10} sm={24}>
            <div className="dottedBox marginB20">
              <div className="subtitle marginB12">增值服务费</div>
              <Item
                colon={false}
                label="短信服务费（￥）/条"
                style={{ margin: 0 }}
              >
                {getFieldDecorator('sms_service_fee', {
                  rules: [
                    {
                      required: true,
                      message: '短信服务费不能为空,且必须为数字',
                    },
                  ],
                })(
                  <Input
                    suffix="元"
                    type="number"
                    style={{ width: '90%' }}
                    placeholder="请输入"
                  />,
                )}
              </Item>
              <div className="subtitle marginB12 marginT24">提现手续费</div>
              <Item
                colon={false}
                label="提现手续费比例"
                style={{ margin: 0 }}
              >
                {getFieldDecorator('withdraw_charge_ratio', {
                  rules: [{ required: true, message: '提现手续费不能为空，且必须为整数' }],
                })(
                  <Input
                    suffix="‰"
                    type="number"
                    style={{ width: '90%' }}
                    placeholder="请输入"
                  />,
                )}
              </Item>
            </div>
          </Col>
        </Row>
        <Row
          gutter={{ md: 8, xl: 48, lg: 48 }}
          className="paddingL20"
        >
          <Button
            type="primary"
            onClick={() => this.validate(1)}
            loading={submitting}
          >
            提交
          </Button>
          <Button
            type="primary"
            style={{ marginLeft: 16, backgroundColor: '#47c479', border: '1px solid #47c479' }}
            onClick={() => this.validate(3)}
            loading={submitting}
          >
            保存
          </Button>
          <Button
            type="primary"
            ghost
            style={{ marginLeft: 16 }}
            onClick={() => router.goBack()}
          >
            取消
          </Button>
        </Row>
      </Card>
    );
  };

  /**
   * 验证保存
   */
  validate = (status: number) => {
    const { form: { validateFieldsAndScroll } } = this.props;

    validateFieldsAndScroll((error, values) => {
      if (!error) {
        const {
          start_end_time,
          delivery_service_fee,
          deposit_service_fee,
          sending_service_fee,
          sms_service_fee,
          ...params
        } = values;

        if (start_end_time) {
          params.start_day = moment(start_end_time[0]).format('YYYY-MM-DD');
          params.end_day = moment(start_end_time[1]).format('YYYY-MM-DD');
        }
        if (delivery_service_fee) {
          params.delivery_service_fee = Math.floor(delivery_service_fee * 100);
        }
        if (deposit_service_fee) {
          params.deposit_service_fee = Math.floor(deposit_service_fee * 100);
        }
        if (sending_service_fee) {
          params.sending_service_fee = Math.floor(sending_service_fee * 100);
        }
        if (sms_service_fee) {
          params.sms_service_fee = Math.floor(sms_service_fee * 100);
        }

        const { fileList }: any = this.state;
        if (fileList.length) {
          params.file_link = fileList[0].url;
        }

        const { match, ContractAdd: { detail } } = this.props;
        if (match.params.pid) {
          params.posthouse_id = detail.posthouse_id;
        }

        if (match.params.pid) {
          params.contract_id = match.params.pid;
        }

        params.status = status;

        if (params.fcs_id && params.fcs_id.key) {
          params.fcs_id = params.fcs_id.key;
        }

        delete params.fileLink;

        /* 提交表单  */
        const { dispatch } = this.props;
        dispatch({
          type: 'posthouseContractAdd/save',
          payload: params,
        });
      }
    });
  };

  /**
   * 上传之前
   */
  beforeUpload(file: any) {
    const formData = new FormData();
    formData.append('file', file);

    upload(`${base_url}/franchise/franchisee/upload_file`, { body: formData }).then(({ code, body }) => {
      if (code === 0) {
        message.success('上传成功');
        const { fileList }: any = this.state;
        fileList[fileList.length - 1].url = body;
        this.setState({ fileList });
      }
    });
  }

  render() {
    return (
      <Fragment>
        <PageHeader />
        <Form hideRequiredMark className="tableListForm">
          {this.renderBasicInfoElem()}
          {this.renderSettlementElem()}
        </Form>
      </Fragment>
    );
  }
}

export default Form.create<PosthouseContractAddInfoProps>()(posthouseContractAdd);
